package com.sun.elasticjob.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sun.elasticjob.entity.File;
import com.sun.elasticjob.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class FileService {

    @Autowired
    private FileMapper fileMapper;

    public List<File> fetchFile(String type, Integer count) {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type)
                    .eq("backed_up", 0)
                    .last("limit " + count);
        return fileMapper.selectList(queryWrapper);
    }

    public void backupFiles(List<File> files) {
        for (File file : files) {
            file.setBackedUp(Boolean.TRUE);
            fileMapper.updateById(file);
        }
    }

    public void generateFile(Long num) {
        LambdaQueryWrapper<File> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(File::getName, "测试数据");
        fileMapper.delete(wrapper);

        for(int i = 1; i <= num; i++) {
            fileMapper.insert(File.builder().name("测试数据" + i).type("text").content("测试数据" + "text" + i).backedUp(Boolean.FALSE).build());
            fileMapper.insert(File.builder().name("测试数据" + i).type("image").content("测试数据" + "image" + i).backedUp(Boolean.FALSE).build());
            fileMapper.insert(File.builder().name("测试数据" + i).type("radio").content("测试数据" + "radio" + i).backedUp(Boolean.FALSE).build());
            fileMapper.insert(File.builder().name("测试数据" + i).type("video").content("测试数据" + "video" + i).backedUp(Boolean.FALSE).build());
        }
    }

    public void reset() {
        QueryWrapper<File> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("backed_up", "1");
        List<File> files = fileMapper.selectList(queryWrapper);
        for (File file : files) {
            file.setBackedUp(Boolean.FALSE);
            fileMapper.updateById(file);
        }
    }

}
